package com.ruoyi.web.controller.system;
import com.ruoyi.system.domain.*;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.BAnjuan;
import com.ruoyi.system.domain.BEEng;
import com.ruoyi.system.domain.entityExcel.entityAJ;
import com.ruoyi.system.domain.entityExcel.entityGC;
import com.ruoyi.system.service.IBAnjuanOldService;
import com.ruoyi.system.service.IBAnjuanService;
import com.ruoyi.system.service.IBEEngService;
import com.ruoyi.system.service.IBGongchengService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 实体工程信息表Controller
 * 
 * @author zzr
 * @date 2023-09-18
 */
@RestController
@RequestMapping("/system/gongcheng")
public class BGongchengController extends BaseController
{
    @Autowired
    private IBGongchengService bGongchengService;

    @Autowired
    private IBAnjuanService bAnjuanService;

    @Autowired
    private IBEEngService beEngService;

    @Autowired
    private IBAnjuanOldService bAnjuanOldService;
    /**
     * 查询实体工程信息表列表
     */
//    //@PreAuthorize("@ss.hasPermi('system:gongcheng:list')")
    @GetMapping("/list")
    public TableDataInfo list(BGongcheng bGongcheng)
    {
        startPage();
        List<BGongcheng> list = bGongchengService.selectBGongchengList(bGongcheng);
        return getDataTable(list);
    }

//    未归档数据列表
    @GetMapping("/noMergerList")
    public TableDataInfo noMergerList(BGongcheng bGongcheng)
    {
        // 设置查询条件，只查询projectStatus字段为0的数据
        bGongcheng.setProjectStatus((long) 0);
        startPage();
        PageHelper.orderBy("creationTime");
        List<BGongcheng> list = bGongchengService.selectBGongchengList(bGongcheng);
        return getDataTable(list);
    }


    /**
     * 导出实体工程信息表列表
     */
//    //@PreAuthorize("@ss.hasPermi('system:gongcheng:export')")
    @Log(title = "实体工程信息表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BGongcheng bGongcheng)
    {
        List<BGongcheng> list = bGongchengService.selectBGongchengList(bGongcheng);
        ExcelUtil<BGongcheng> util = new ExcelUtil<BGongcheng>(BGongcheng.class);
        util.exportExcel(response, list, "实体工程信息表数据");
    }

    /**
     * 获取实体工程信息表详细信息
     */
//    //@PreAuthorize("@ss.hasPermi('system:gongcheng:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(bGongchengService.selectBGongchengById(id));
    }

    /**
     * 新增实体工程信息表
     */
//    //@PreAuthorize("@ss.hasPermi('system:gongcheng:add')")
    @Log(title = "实体工程信息表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BGongcheng bGongcheng)
    {
        return toAjax(bGongchengService.insertBGongcheng(bGongcheng));
    }

    /**
     * 修改实体工程信息表
     */
//    //@PreAuthorize("@ss.hasPermi('system:gongcheng:edit')")
    @Log(title = "实体工程信息表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BGongcheng bGongcheng)
    {
        return toAjax(bGongchengService.updateBGongcheng(bGongcheng));
    }

    @GetMapping("getTemplate")
    public ResponseEntity<byte[]> getTemplate(){
        return bGongchengService.getTemplate();
    }

    /**
     * excel导入实体档案
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/importGCExcel")
    public AjaxResult importGCExcel(MultipartFile file, Long classId) throws Exception
    {
        ExcelUtil<entityGC> util = new ExcelUtil<entityGC>(entityGC.class);
        List<entityGC> entityGCList = util.importExcel(file.getInputStream(),0);
        ExcelUtil<entityAJ> util1 = new ExcelUtil<entityAJ>(entityAJ.class);
        List<entityAJ> entityAJList = util1.importExcel("案卷信息表",file.getInputStream(), 0);
        String message = bGongchengService.importGCExcel(entityGCList, entityAJList, classId);
        return AjaxResult.success(message);
    }

    /**
     * 删除实体工程信息表
     */
//    //@PreAuthorize("@ss.hasPermi('system:gongcheng:remove')")
    @Log(title = "实体工程信息表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(bGongchengService.deleteBGongchengByIds(ids));
    }

     //查询根据根据年度获得统计
    @GetMapping("/getNianDuTongJi")
    public Map<Object, Object> getNianDuTongJi(){
        Map<Object, Object> ansMap = new HashMap<Object, Object>();
        List<TongJiTemp> tongJiTemps = bGongchengService.getNianDuTongJi();
        //获取长度
        int count = tongJiTemps.size();
        int[] years = new int[count];
        int[] volumeNums = new int[count];
        for(int i = 0; i < count; i++) {
            volumeNums[i] = tongJiTemps.get(i).getNum();
            years[i] = Integer.parseInt(tongJiTemps.get(i).getText());
        }
        //3.push
        ansMap.put("years", reverseData(years));
        ansMap.put("volumeNums", reverseData(volumeNums));
        return ansMap;
    }

    // 查询根据分类获得统计
    @GetMapping("/getFenLeiTongJi")
    public Map<Object, Object> getFenLeiTongJi(){
        Map<Object, Object> ansMap = new HashMap<Object, Object>();
        List<TongJiTemp> tongJiTemps = bGongchengService.getFenLeiTongJi();
        //获取长度
        int count = tongJiTemps.size();
        String[] classes = new String[count];
        int[] volumeNums = new int[count];
        for(int i = 0; i < count; i++) {
            classes[i] = tongJiTemps.get(i).getText();
            volumeNums[i] = tongJiTemps.get(i).getNum();
        }
        //3.push
        ansMap.put("classes", classes);
        ansMap.put("volumeNums", volumeNums);
        return ansMap;
    }

//    // 查询根据根据年度获得统计
//    @GetMapping("/getNianDuTongJi")
//    public List<TongJiTemp> getNianDuTongJi(){
//        return bGongchengService.getNianDuTongJi();
//    }

    // 查询根据分类获得统计
//    @GetMapping("/getFenLeiTongJi")
//    public List<TongJiTemp> getFenLeiTongJi(){
//        return bGongchengService.getFenLeiTongJi();
//    }

    /**
     * 反转数组数据，为前端展示数据做处理
     * @param data
     * @return
     */
    private int[] reverseData(int[] data) {
        int[] ans = new int[data.length];
        for (int i = 0; i < data.length; i++) {
            ans[i] = data[data.length - 1 - i];
        }
        return ans;
    }
    /**
     * 绑定实体档案
     * 1.将电子档案b_e_eng的id插入到b_gongcheng的eid中，并将b_gongcheng的bindStatus置为1
     * 2.根据b_gongcheng的eid前的id，找b_anjuan的gid们
     * 3.将b_e_eng的id插入到b_anjuan的gid们的yuLiuD中，并将yuliB置为1
     * 4.将b_e_eng的projectStatus设为4,yuliuA设为2，yuliuC设为gid
     *
     */
    @PostMapping("/bindShitiByDianzi/{eeid}/{gid}")
    public AjaxResult bindShitiByDianzi(@PathVariable String eeid, @PathVariable String gid)
    //eeid是电子档案的id， gid是实体档案的id
    {
        try {
            BGongcheng gongCheng = bGongchengService.selectBGongchengById(gid);
            if(gongCheng != null){
                gongCheng.setEid(eeid);
                gongCheng.setBindStatus(1L);
                if(gongCheng.getAnJuanShu() >= gongCheng.getYuliuA()) {
                    bGongchengService.updateBGongcheng(gongCheng);
                    BAnjuan[] anJuanes = bAnjuanService.selectByGid(gid);
                    if(anJuanes.length>0){
                        for (BAnjuan bAnjuan : anJuanes) {
                            bAnjuan.setYuLiuB(1L);
                            bAnjuan.setYuLiuD(eeid);
                            bAnjuanService.updateBAnjuan(bAnjuan);
                        }
                    }
                    BEEng beeng = beEngService.selectBEEngById(eeid);
                    beeng.setProjectStatus(4L);
                    beeng.setYuLiuA(2L);
                    beeng.setYuLiuC(gid);
                    if(beEngService.updateBEEng(beeng) != 1) {
                        return AjaxResult.error("ERROR_DB_OPERATION_FALSED");
                    }
                }
                else {
                    return AjaxResult.error("ERROR_INVALID_PARAMETER");
                }

            }
            else {
                return AjaxResult.error("ERROR_DB_OPERATION_FALSED");
            }

        } catch (Exception e){
            e.printStackTrace();
        }
        return success();
    }

    /**
     * 解绑档案
     * 1.将电子档案b_e_eng的id插入到b_gongcheng的eid中，并将b_gongcheng的bindStatus置为1
     * 2.根据b_gongcheng的eid前的id，找b_anjuan的gid们
     * 3.将b_e_eng的id插入到b_anjuan的gid们的yuLiuD中，并将yuliB置为1
     * 4.将b_e_eng的projectStatus设为4,yuliuA设为2，yuliuC设为gid
     *
     */
    @PostMapping("/cancelEngBind/{eeid}/{bindType}")
    public AjaxResult cancelEngBind(@PathVariable String eeid, @PathVariable Integer bindType)
    //eeid是电子档案的id， bindType是yuLiuA（0：未绑定 2：绑定了实体档案  3：绑定了旧实体案卷）
    {
        try {
            BEEng beeng = beEngService.selectBEEngById(eeid); //获取某条电子档案
            if(bindType == 3) { //如果yuliuA是3(绑定了旧实体案卷)
                if(bAnjuanOldService.updateAnJuanByEEid(eeid) < 1){
                    return AjaxResult.error("ERROR_DB_OPERATION_FALSED");
                }
            }
            else if(bindType == 2) //如果yuliuA是2(绑定了实体档案)
            {
                HashMap<String,Object> pMap = new HashMap<String, Object>();
                pMap.put("eeid", null);  //将eeid的值赋值到eeid中（b_anjuan.yuLiuD: null ）
                pMap.put("bindState", 0);   //0赋给bindState （b_anjuan.yuliuB : 1-> 0）
                pMap.put("sql", "yuLiuB=1 and yuLiuD = '"+eeid+"'"); //where子句判断条件
                if(bAnjuanService.updateAnJuanBySql(pMap) < 1){                                     //更新b_anjuan表
                    return AjaxResult.error("ERROR_DB_OPERATION_FALSED");
                }
                BGongcheng gongcheng = bGongchengService.selectBGongchengById(beeng.getYuLiuC());  //根据b_e_eng.yuliuC 找到实体档案类
                gongcheng.setYuliuB(null); //让实体档案类的yuliuB变为null
                gongcheng.setEid(null); //让实体档案类的eid变为null !!!!!!
                gongcheng.setBindStatus(0L); //让实体档案类的bindStatus变为0

                if(bGongchengService.updateBGongcheng(gongcheng) < 1){                              //更新b_gongcheng表
                    return AjaxResult.error("ERROR_DB_OPERATION_FALSED");
                }
            }
            beeng.setProjectStatus(2L);  //将b_e_eng的projectStatus: 4 -> 2
            beeng.setYuLiuA(0L);         //将b_e_eng的yuliuA: 2 -> 0
            beeng.setYuLiuC(null);       //将b_e_eng的yuliuC: null !!!!!
            if(beEngService.updateBEEng(beeng) != 1){                                                //更新b_e_eng表
                return AjaxResult.error("ERROR_DB_OPERATION_FALSED");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return success();
    }

    /**
     * 绑定旧实体案卷
     *
     */
    @PostMapping("/bindNewDzOldAnjuan/{eeid}/{bindAnJuanIdes}")
    public AjaxResult bindNewDzOldAnjuan(@PathVariable String eeid, @PathVariable String[] bindAnJuanIdes){
        if(bindAnJuanIdes.length > 0){
            for(String gaid: bindAnJuanIdes){
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("recid", gaid);
                map.put("yuliu_c", 2);
                map.put("eng_id", eeid);
                if(bAnjuanOldService.updateAnJuanBingStatus(map) < 1){
                    return AjaxResult.error("ERROR_DB_OPERATION_FALSED");
                }
            }
            BEEng beeng = beEngService.selectBEEngById(eeid);
            if(beeng.getProjectStatus() < 3){
                beeng.setProjectStatus(4L);
                beeng.setYuLiuA(3L);
                if(beEngService.updateBEEng(beeng) != 1){
                    return AjaxResult.error("ERROR_DB_OPERATION_FALSED");
                }
            }
        }else{
            return AjaxResult.error("ERROR_INVALID_PARAMETER");
        }
        return success();
    }


}
